package com.team.order.listener;

import com.team.order.constants.MqConstants;
import com.team.order.domain.Order;
import com.team.order.domain.vo.OrderVO;
import com.team.order.service.IAdminOrderService;
import com.team.order.utils.PaymentUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final IAdminOrderService orderService;
    // private final PayClient payClient;
    private final PaymentUtil paymentUtil;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME), exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"), key = MqConstants.DELAY_ORDER_KEY))
    public void listenOrderDelayMessage(Long orderId) {
        // 1.查询订单
        OrderVO orderVO = orderService.selectOrderById(orderId);
        // 2.检测订单状态，判断是否已支付
        if (orderVO == null || orderVO.getPayStatus() != 1) {
            // 订单不存在或者已经支付
            return;
        }
        // 3.未支付，需要查询支付流水状态
        String s = paymentUtil.queryPaymentStatus(String.valueOf(orderVO.getOrderId()));
        // PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(orderId);
        // 4.判断是否支付
        if (!Objects.equals(s, "NOT_FOUND")) {
            // 4.1.已支付，标记订单状态为已支付
            Order order = new Order();
            order.setPayStatus(1L);
            orderService.updateOrder(order);
            // orderService.markOrderPaySuccess(orderId);
        } else {
            // 4.2.未支付，取消订单，回复库存
            orderService.deleteOrderById(orderId);
        }
    }
}
